package com.huayue.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.huayue.annotation.LogAnno;
import com.huayue.entity.*;
import com.huayue.service.*;
import com.huayue.util.DateHelper;
import com.huayue.util.OrderNumberHelper;
import com.huayue.util.PageHelper;

/**
 * 入住订单
 */
@Controller
@RequestMapping("/roomRealOrder")
public class RoomRealOrderController {
    @Autowired
    RoomRealOrderService svc;
    @Autowired
    EmployeeService esvc;
    @Autowired
    RoomTypeService rsvc;
    @Autowired
    CustomerService csvc;

    @Autowired
    RoomPredictOrderService rposvc;

    @Autowired
    RoomStatusService rssvc;

    @Autowired
    RoomChangeService rcsvc;

    @Autowired
    HousekeepOrderService hkOService;

    BaseController bc = new BaseController();

    @RequestMapping("/toAdd")
    public ModelAndView toAdd(RoomRealOrder room_real_order, String checkDate, Integer days) {
        FastJsonJsonView view = new FastJsonJsonView();
        view.addStaticAttribute("orderNumber", OrderNumberHelper.getOrderNumber(OrderNumberHelper.RZDORDER, "RZD"));
        List<Map<String, Object>> room = rposvc.findNullfrom(checkDate, days);
        // 去除脏房
        for (int i = room.size() - 1; i >= 0; i--) {
            Map<String, Object> item = room.get(i);
            if (4 == Integer.valueOf(item.get("status_id").toString())) {
                try {
                    room.remove(item);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }
        view.addStaticAttribute("room", room);
        return new ModelAndView(view);
    }

    @RequestMapping("/toChange")
    public ModelAndView toChange(RoomRealOrder room_real_order, RoomChange roomChange) {
        FastJsonJsonView view = new FastJsonJsonView();
        view.addStaticAttribute("roomInfo", rcsvc.findOneRoom(roomChange));
        view.addStaticAttribute("roomtype", rcsvc.findType());
        view.addStaticAttribute("overDays", rcsvc.findOverDaysByRoomId(roomChange.getRoom_type_id()));
        // 需查询原房间的入住天数
        RoomRealOrder order = svc.findDaysAndInTimeByRoomId(roomChange.getRoom_type_id());
        view.addStaticAttribute("room", rposvc.findNullfrom(DateHelper.DateToStringShort(order.getRealInTime()),
            Integer.valueOf(order.getDays().intValue())));
        return new ModelAndView(view);

    }

    @LogAnno(operateType = "转房操作")
    @RequestMapping("/Change")
    public ModelAndView Change(RoomChange roomChange, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("USER");
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> map = rcsvc.findRoomReal(roomChange);
        int rid = Integer.valueOf(map.get("rid").toString());
        int cid = Integer.valueOf(map.get("cid").toString());
        // 选用新房价
        if (roomChange.getPriceFlag() == 1) {
            rcsvc.insertNewRealDetails(rid, cid, roomChange);
        } else {
            rcsvc.insertOldRealDetails(rid, cid, roomChange);
        }

        rcsvc.updateRealDetails(rid, roomChange);
        // 将押金换至新房间
        rcsvc.updateRoomDeposit(rid, roomChange.getOldId(), roomChange.getNewId());
        // 添加房务订单
        HousekeepOrder order = new HousekeepOrder();
        String orderNumber = OrderNumberHelper.getOrderNumber(OrderNumberHelper.FWORDER, "FW");
        order.setOrdernumber(orderNumber);
        OrderNumberHelper.removeOrderNumber(OrderNumberHelper.FWORDER, orderNumber);
        order.setEnployee_id_apply(user.getId());
        order.setWorkdate_begin(new Date());
        List<HousekeepOrderDetails> list = new ArrayList<HousekeepOrderDetails>();
        HousekeepOrderDetails detail = new HousekeepOrderDetails();
        detail.setRoom_id(roomChange.getOldId());
        detail.setHousekeep_id(1);
        detail.setRemark("转房");
        list.add(detail);
        // 原房态不为空房时添加房务订单
        if (detail.getHousekeep_id() != 1) {
            hkOService.addDetails(order, list);
        }

        int a = rcsvc.updateNewRoomStatus(roomChange);
        int b = rcsvc.updateOldRoomStatus(roomChange);
        if (a > 0 && b > 0) {
            view.addStaticAttribute("icon", 1);
            view.addStaticAttribute("msg", "换房成功！");
        } else {
            view.addStaticAttribute("icon", 2);
            view.addStaticAttribute("msg", "换房失败！");
        }
        return new ModelAndView(view);

    }

    /**
     * 清除订单号
     *
     */
    @RequestMapping("/close")
    public ModelAndView close(RoomRealOrder roomRealOrder) {
        FastJsonJsonView view = new FastJsonJsonView();
        OrderNumberHelper.removeOrderNumber(OrderNumberHelper.RZDORDER, roomRealOrder.getOrdernumber());
        view.addStaticAttribute("code", 0);
        return new ModelAndView(view);
    }

    @LogAnno(operateType = "添加-入住订单")
    @RequestMapping("/add")
    public ModelAndView add(@RequestBody String json, HttpServletRequest request) {
        // 获取session中该用户信息
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("USER");
        // 格式化json数据
        JSONObject jsonData = JSON.parseObject(json);
        // 创建押金订单信息
        RoomDeposit deposit = new RoomDeposit();
        deposit.setPrice(BigDecimal.valueOf(Double.valueOf(jsonData.get("depositPrice").toString())));
        deposit.setCashpay(jsonData.get("depositType").toString());
        deposit.setEmployee_id_income(user.getId());

        // 添加顾客信息
        Customer customer = new Customer();
        customer.setRealname(jsonData.get("realname").toString());
        customer.setPhone(jsonData.get("phone").toString());
        customer.setIdnumber(jsonData.get("idNumber").toString());
        String sex = jsonData.get("sex").toString();
        if ("男".equals(sex)) {
            customer.setSex("0");
        } else {
            customer.setSex("1");
        }
        // 创建订单信息
        RoomRealOrder order = new RoomRealOrder();
        order.setEmployeeId(Long.valueOf(user.getId()));
        order.setOrdernumber(String.valueOf(jsonData.get("orderNumber")));
        order.setRealInTime(DateHelper.StringToDateShort(jsonData.get("realInTime").toString()));
        order.setRealOutTime(DateHelper.StringToDateShort(jsonData.get("realOutTime").toString()));
        order.setRemark(jsonData.get("remark").toString());
        order.setDays(Long.valueOf(jsonData.get("days").toString()));
        order.setPersonNumber(Long.valueOf(jsonData.get("num").toString()));
        order.setPayment(jsonData.get("totalPay").toString());
        JSONArray jsonArray = jsonData.getJSONArray("table");
        // 获取订单详情
        List<RoomRealOrderDetails> details = JSONArray.parseArray(jsonArray.toString(), RoomRealOrderDetails.class);
        // 将订单信息和订单详情传至service进行处理
        boolean result = svc.addDetails(order, details, customer, deposit);
        // 将临时订单号销毁
        OrderNumberHelper.removeOrderNumber(OrderNumberHelper.RZDORDER, order.getOrdernumber());
        // 返回数据给页面
        FastJsonJsonView view = new FastJsonJsonView();
        view.addStaticAttribute("code", 0);
        if (result) {
            view.addStaticAttribute("icon", 1);
            view.addStaticAttribute("msg", "入住成功！");
        } else {
            view.addStaticAttribute("icon", 2);
            view.addStaticAttribute("msg", "入住失败！");
        }
        return new ModelAndView(view);
    }

    @LogAnno(operateType = "修改-入住订单")
    @RequestMapping("/update")
    public ModelAndView update(RoomRealOrder room_real_order) {
        return bc.update(svc, room_real_order);
    }

    @LogAnno(operateType = "删除-入住订单")
    @RequestMapping("/delete")
    public ModelAndView delete(RoomRealOrder room_real_order) {
        return bc.delete(svc, room_real_order);
    }

    @RequestMapping("/findOne")
    public ModelAndView findOne(RoomRealOrder room_real_order) {
        return bc.findOne(svc, room_real_order);
    }

    @RequestMapping("/findPage")
    public ModelAndView findPage(PageHelper page, RoomRealOrder room_real_order) {
        return bc.findPage(svc, page, room_real_order, room_real_order);
    }

    @RequestMapping("/findDetails")
    public ModelAndView findDetails(String id) {
        FastJsonJsonView view = new FastJsonJsonView();
        view.addStaticAttribute("code", 0);
        RoomRealOrder roomRealOrder = new RoomRealOrder();
        roomRealOrder.setId(Long.valueOf(id));
        view.addStaticAttribute("order", svc.findOne(roomRealOrder));
        view.addStaticAttribute("data", svc.findDetails(id));
        view.addStaticAttribute("room", svc.findfrom());
        view.addStaticAttribute("roomPrice", svc.findRoom_deposit_price(id));
        // view.addStaticAttribute("customer", csvc.findAll());
        return new ModelAndView(view);
    }

    @LogAnno(operateType = "客户到店")
    @RequestMapping("/arrival")
    public ModelAndView arrival(RoomRealOrderDetails detail, String dayOut, String preprice, BigDecimal dprice,
        Integer people, Customer customer, RoomDeposit deposit, HttpServletRequest request) {
        // 获取session中该用户信息
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("USER");
        FastJsonJsonView view = new FastJsonJsonView();
        view.addStaticAttribute("code", 0);
        // 完善RoomRealOrder信息
        RoomRealOrder order = new RoomRealOrder();
        order.setOrdernumber(OrderNumberHelper.getOrderNumber(OrderNumberHelper.RZDORDER, "RZD"));
        order.setEmployeeId(Long.valueOf(user.getId()));
        order.setTotalprice(new BigDecimal(preprice));
        order.setRemark("");
        order.setRealInTime(DateHelper.StringToDateShort(DateHelper.DateToStringShort(new Date())));
        order.setRealOutTime(DateHelper.StringToDateShort(dayOut));
        order.setPersonNumber(Long.valueOf(people));
        order.setPayment("");
        Date out = DateHelper.StringToDateShort(dayOut);
        Integer days = DateHelper.getDateRangeNumber(new Date(), out);
        order.setDays(Long.valueOf(days));
        // 完善订单详情信息
        List<RoomRealOrderDetails> details = new ArrayList<RoomRealOrderDetails>();
        detail.setName(customer.getRealname());
        detail.setIdnumber(customer.getIdnumber());
        details.add(detail);
        deposit.setRoom_id(detail.getRoom_id());
        deposit.setEmployee_id_income(user.getId());
        deposit.setPrice(dprice);
        deposit.setCashpay("");

        svc.addDetails(order, details, customer, deposit);
        // 将预定订单的状态改为1 根据roomid
        // 将预定订单详情的状态改为1 根据roomid
        rposvc.updatePredictOrderStatus(detail.getRoom_id());

        // 将当前顾客的信息绑定在最新修改的房间状态的房间上。
        rssvc.updateCustomerByNewTime();
        view.addStaticAttribute("icon", 1);
        view.addStaticAttribute("msg", "入住成功！");
        return new ModelAndView(view);
    }

    @RequestMapping("/toRenew")
    public ModelAndView toRenewRoom(Integer RoomId) {
        FastJsonJsonView view = new FastJsonJsonView();
        // 查询该房间是否可续住以及续住天数 -- 查预定订单中有没有该房间，若有则将预定房间的时间返回
        // 查询该房间的入住信息
        view.addStaticAttribute("code", 0);
        view.addStaticAttribute("info", svc.findRoomRenew(RoomId));
        return new ModelAndView(view);
    }

    @LogAnno(operateType = "客房续住")
    @RequestMapping(value = "/renew", method = RequestMethod.POST)
    public ModelAndView renewRoom(String roomId, String days, BigDecimal addPrice) {
        FastJsonJsonView view = new FastJsonJsonView();

        view.addStaticAttribute("code", 0);

        boolean r = svc.renewRoom(Integer.valueOf(roomId), Integer.valueOf(days), addPrice);
        if (r) {
            view.addStaticAttribute("icon", 1);
            view.addStaticAttribute("msg", "续房成功");
        } else {
            view.addStaticAttribute("icon", 2);
            view.addStaticAttribute("msg", "续房失败");
        }
        return new ModelAndView(view);
    }
}
